import React from 'react'
import Chart from 'react-apexcharts'
import { Query } from 'react-apollo'
import Loading from 'components/loading'
import getUserWorkTime from 'graphql/project/task/user/userWorkTime.graphql'
import moment from 'moment'
import { Grid, Label } from 'semantic-ui-react'

const getData = () => {
  const result = []
  for (let i = 0; i < 24; i += 1) {
    result.push({ x: `${i}点`, y: 0 })
  }
  return result
}

const getSeriesData = () => {
  const result = []
  for (let i = 0; i < 12; i += 1) {
    result.push({
      name: `${i * 5}-${(i + 1) * 5}分`,
      data: getData(),
    })
  }
  return result
}

export default class HeatmapChart extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      options: {
        dataLabels: {
          enabled: false,
        },
        colors: ['#008FFB'],
        title: {
          text: '分时工作饱和度',
        },
      },
    }
  }

  render() {
    const { options } = this.state
    const {
      name, start, end, pid,
    } = this.props
    const series = getSeriesData()
    const variablesFinal = {
      name,
      pid,
      start,
      end,
    }
    return (
      <Query query={getUserWorkTime} variables={variablesFinal} fetchPolicy="network-only" notifyOnNetworkStatusChange>
        {({ loading, error, data }) => {
          if (loading) return <Loading />
          if (error) return `Error! ${error.message}`
          let workTime = 0
          let workCount = 0
          if (data && data.annotation) {
            workCount = data.annotation.length
            data.annotation.map((ann) => {
              const minuteIndex = Math.floor(moment(ann.create_at).get('minute') / 5)
              const hourIndex = moment(ann.create_at).get('hour')
              if (series[minuteIndex].data[hourIndex].y === 0 ) {
                workTime += 5
              }
              series[minuteIndex].data[hourIndex].y += 1
            })
          }
          return (
            <Grid>
              <Grid.Row centered columns={1}>
                <Grid.Column>
                  <Chart options={options} series={series} type="heatmap" height="350" />
                </Grid.Column>
              </Grid.Row>
              <Grid.Row centered columns={3}>
                <Grid.Column textAlign="center">
                  <Label circular style={{ backgroundColor: '#008FFB' }} empty key="red" />
                  {`工作: ${Math.floor(workTime / 60)}小时${workTime % 60}分钟 (标注数量: ${workCount})`}
                </Grid.Column>
              </Grid.Row>
            </Grid>
          )
        }}
      </Query>
    )
  }
}
